package com.fuli.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.fuli.app.common.ActionResult;
import com.fuli.app.common.ErrorInfo;
import com.fuli.app.common.Pagination;
import com.fuli.app.common.WxConfig;
import com.fuli.app.dto.MessageDTO;
import com.fuli.app.dto.query.MessageQueryDTO;
import com.fuli.app.service.MessageService;
import com.fuli.app.util.EntityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.weixin4j.WeixinException;
import org.weixin4j.http.HttpsClient;
import org.weixin4j.http.Response;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "报名")
@RestController
@RequestMapping("/Message")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @ApiOperation(value = "报名", notes = "<b>必填属性：</b><br>" +
            "1.id 主键32位UUID，调用/message/uuid获取<br/>" +
            "2.name 名称<br/>" +
            "3.orderId 订单号<br/>" +
            "4.code 微信code<br/>" +
            "5.content 班级<br/>" +
            "6.avatarUrl 用户头像<br/>" +
            "7.nickName 用户昵称<br/>" +
            "8.openId 微信唯一标识,调用/message/openid获取<br/>" +
            "<i style='color:red;font-weight:600'>注意，这里id是由前端传给后台的</i><br>")
    @PostMapping(value = "/add")
    public ActionResult<String> add(@ApiParam("报名DTO") @RequestBody MessageDTO dto) {
        List<ErrorInfo> errors = new ArrayList<>();
        if (StringUtils.isEmpty(dto.getId()))
            errors.add(new ErrorInfo(0, "id为空"));
        if (StringUtils.isEmpty(dto.getName()))
            errors.add(new ErrorInfo(0, "姓名为空"));
//        if (StringUtils.isEmpty(dto.getTel()))
//            errors.add(new ErrorInfo(0, "联系电话为空"));
//        if (StringUtils.isEmpty(dto.getEmail()))
//            errors.add(new ErrorInfo(0, "电子邮箱为空"));
        if (StringUtils.isEmpty(dto.getClassName()))
            errors.add(new ErrorInfo(0, "班级为空"));
        if (StringUtils.isEmpty(dto.getOrderId()))
            errors.add(new ErrorInfo(0, "订单号为空"));
        if (StringUtils.isEmpty(dto.getCode()))
            errors.add(new ErrorInfo(0, "微信code为空"));
        if (StringUtils.isEmpty(dto.getAvatarUrl()))
            errors.add(new ErrorInfo(0, "微信头像地址为空"));
        if (StringUtils.isEmpty(dto.getNickName()))
            errors.add(new ErrorInfo(0, "微信昵称为空"));
        if (!errors.isEmpty())
            return new ActionResult<>(errors);
        return messageService.add(dto);
    }

    @ApiOperation("删除报名")
    @DeleteMapping(value = "/delete/{id}")
    public ActionResult<String> delete(@ApiParam("id") @PathVariable String id) {
        return messageService.delete(id);
    }

    @ApiOperation("批量删除报名")
    @DeleteMapping(value = "/batchDelete")
    public ActionResult<List<String>> batchDelete(@ApiParam("报名id数组") @RequestParam List<String> ids) {
        return messageService.batchDelete(ids);
    }

    @ApiOperation("获取报名")
    @GetMapping(value = "/get/{id}")
    public ActionResult<MessageDTO> get(@ApiParam("id") @PathVariable String id) {
        return messageService.get(id);
    }

    @ApiOperation("分页获取未处理报名")
    @GetMapping(value = "/pageQuery")
    public ActionResult<Pagination<MessageDTO>> listByQueryDTO(@ApiParam("报名查询DTO") @ModelAttribute MessageQueryDTO QueryDTO) {
        return messageService.listByQueryDTO(QueryDTO);
    }
    @ApiOperation("分页获取所有报名")
    @GetMapping(value = "/pageAllQuery")
    public ActionResult<Pagination<MessageDTO>> listAllByQueryDTO(@ApiParam("报名查询DTO") @ModelAttribute MessageQueryDTO QueryDTO) {
        return messageService.listAllByQueryDTO(QueryDTO);
    }

    @ApiOperation("标记处理")
    @PutMapping(value = "/deal{id}")
    public ActionResult<String> deal(@ApiParam("id") @PathVariable String id) {
        return messageService.deal(id);
    }

    @ApiOperation("批量标记处理")
    @PutMapping(value = "/batchDeal")
    public ActionResult<List<String>> batchDeal(@ApiParam("报名id数组") @RequestParam List<String> ids) {
        return messageService.batchDeal(ids);
    }

    @ApiOperation("获取32位id")
    @GetMapping(value = "/uuid")
    public ActionResult<String> getUUid() {
        return new ActionResult<>(EntityUtils.uuid());
    }

    @ApiOperation("获取openId")
    @GetMapping(value = "/openId")
    public ActionResult<String> openId(@ApiParam(value = "code") @RequestParam String code) throws WeixinException {
        String openid = "";
        //拼接参数
        String param = "?grant_type=" + WxConfig.grant_type + "&appid=" + WxConfig.appid + "&secret=" + WxConfig.secret + "&js_code=" + code;

        //创建请求对象
        HttpsClient http = new HttpsClient();
        //调用获取access_token接口
        Response res = http.get("https://api.weixin.qq.com/sns/jscode2session" + param);
        //根据请求结果判定，是否验证成功
        JSONObject jsonObj = res.asJSONObject();
        if (jsonObj != null) {
            Object errcode = jsonObj.get("errcode");
            if (errcode != null) {
                return new ActionResult<>(0, "获取失败");
            }
            openid = jsonObj.getString("openid");
        }
        return new ActionResult<>(openid);
    }


}
